//
//  QSTextEditor.swift
//  chat
//
//  Created by 1 on 2023/3/30.
//

import SwiftUI

struct QSTextEditor: View {
    var placeholder: String
    @Binding var text: String
    var editingChanged: (Bool)->() = { _ in }
    var commit: ()->() = { }
    var fontSize: CGFloat = 16
    var body: some View {
        ZStack(alignment: .leading) {

            let textEditor = TextEditor(text: $text)
                .foregroundColor(MBAColor.com_white.color)
                .font(.system(size: fontSize))
                .onSubmit {
                    self.commit()
                }.onChange(of: text) { _ in
                    self.editingChanged(true)
                }
                .padding(.horizontal,12)
                .padding(.vertical,8)
            if #available(iOS 16.0, *) {
                textEditor.scrollContentBackground(.hidden)
            }else{
                textEditor
            }
            
            if text.isEmpty {
                VStack{
                    Text(placeholder).foregroundColor(MBAColor.com_placehoder.color).font(.system(size: fontSize))
                    Spacer()
                }
                .padding(16)
                .allowsHitTesting(false)
            }else{
                HStack{
                    Spacer()
                    VStack{
                        Spacer()
                        Text("清空").foregroundColor(MBAColor.com_gblue.color).font(.system(size: fontSize))
                            .onTapGesture {
                                text = ""
                            }
                    }
                }
                .padding(16)
            }
        }
    }
}

struct QSTextEditor_Previews: PreviewProvider {
    static var previews: some View {
        QSTextEditor(placeholder: "提示", text: .constant("a"))
            .background(.red)
            .frame(height: 100)
    }
}
